import base64, hashlib, random, binascii

TEXT_MAX_LENGTH = 1000

CRYPT_SECRET = "HDNDV83JD73GS"

def id2ids(id):
    
    ids = str(id)
    
    ids = base64.b64encode(ids)
    
    rand = random.Random(CRYPT_SECRET).randrange

    ids = [chr(ord(elem)^rand(256)) for elem in ids]
    
    return binascii.hexlify(''.join(ids))
    
def ids2id(ids):
    
    if not ids: return False
    
    ids = binascii.unhexlify(ids)
    
    rand = random.Random(CRYPT_SECRET).randrange
    
    ids = [chr(ord(elem)^rand(256)) for elem in ids]
    
    ids = ''.join(ids)

    return int(base64.b64decode(ids))

def clean(txt):
    
    txt = txt.strip();
    
    if len(txt) > TEXT_MAX_LENGTH:
        txt = txt[0:TEXT_MAX_LENGTH]
        
    return txt
                 
def toInt(str):
    
    if str == None: return 0
    
    if str.isdigit(): return int(str)

    return 0
    
def str2date(mytime, time_format = "%Y-%m-%d %H:%M:%S"):
    
    import time, datetime

    return datetime.datetime.fromtimestamp(time.mktime(time.strptime(mytime, time_format)))

def formatRange(price_from, price_to):
        
    limit = 1000000
        
    if price_from > limit:
        price_from = limit
    if price_to > limit:
        price_to = limit
            
    if price_from > price_to:
        tmp = price_from
        price_from = price_to
        price_to = tmp
    elif price_to != 0 and price_to == price_from:
        price_to = 0
            
    return price_from, price_to

def getCode(len):
    alphabet = 'abcdefghijklmnopqrstuvwxyz'
    string=''

    for x in random.sample(alphabet, len):
        string+=x
            
    return string.upper()


def intersect(seq1, seq2):
    res = []
    for x in seq1:
        if x in seq2:
            res.append(x)
    return res

def xssescape(text):
    from cgi import escape
    
    """Gets rid of < and > and & and, for good measure, :"""
    return escape(text, quote=True).replace(':','&#58;')

def getPlatformID(key):
    
    if "schueler" in key: return 1
    if "studivz" in key: return 2
    if "meinvz" in key: return 2
    if "www.vz.net" in key: return 2
    
    return 0